import frappe
import openpyxl  
import os

@frappe.whitelist()
def upload_xlsx_file(file_path,sheet_name=None):

    _, file_extension =os.path.splitext(file_path)
    if file_extension.lower() != ".xlsx":
        frappe.throw("Only .xlsx files are allowed")

    if "private" in file_path:
        file_path = frappe.get_site_path() + file_path
    else:
        file_path = frappe.get_site_path() + "/public" + file_path

    # 打开 Excel 文件  
    workbook = openpyxl.load_workbook(file_path)  
      
    # 获取指定的工作表，如果没有指定则使用第一个工作表  
    if sheet_name:  
        sheet = workbook[sheet_name]  
    else:  
        sheet = workbook.active  
      
    # 获取第一行的标题（列名）  
    headers = [cell.value for cell in sheet[1]]  
      
    # 存储所有行数据的列表，每行数据为字典形式  
    data = []  
      
    # 遍历每一行（从第四行开始，因为第一行是标题）  
    for row in sheet.iter_rows(min_row=4, values_only=True):  
        row_dict = dict(zip(headers, row))  
        data.append(row_dict)  
      
    return data  





import os
#  这就是上传文件啦
def uploadFileManagerFolder(file_name, file_path):
    # print(os.getcwd())
    with open(file_path, 'rb') as f:
        file_data = f.read()
    # Create a new File document
    _file = frappe.get_doc({
        "doctype": "File",
        "file_name": file_name,
        "folder": "Home",
        "file_type": "XLSX",
        "content": file_data,
        "is_private": 1
    })
    _file.save()

